import tkinter as tk
from tkinter import messagebox, ttk, filedialog
from number_generator import NumberGenerator

class NumberGeneratorUI:
    def __init__(self):
        self.root = tk.Tk()
        self.setup_ui()

    def setup_ui(self):
        """初始化号码生成界面"""
        self.root.title("号码生成器")
        self.root.geometry("600x550")

        frame = ttk.Frame(self.root, padding="20")
        frame.pack(fill=tk.BOTH, expand=True)
        # 添加返回按钮 - 放在第一行第一列
        back_btn = ttk.Button(frame, text="返回主界面", command=self.back_to_main)
        back_btn.grid(row=0, column=0, sticky=tk.W, pady=5)

        # 生成数量设置 - 放在第二行
        ttk.Label(frame, text="生成数量:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
        self.count_var = tk.StringVar(value="1")
        count_entry = ttk.Entry(frame, textvariable=self.count_var, width=10)
        count_entry.grid(row=1, column=1, sticky=tk.W, padx=5, pady=5)

        # 生成类型选择 - 放在第一行第二列
        type_frame = ttk.LabelFrame(frame, text="生成类型", padding=10)
        type_frame.grid(row=0, column=1, rowspan=2, padx=10, pady=5, sticky=tk.N)

        self.type_var = tk.StringVar(value="credit")
        ttk.Radiobutton(type_frame, text="统一信用代码", variable=self.type_var, value="credit").pack(anchor=tk.W, pady=3)
        ttk.Radiobutton(type_frame, text="身份证号码", variable=self.type_var, value="id").pack(anchor=tk.W, pady=3)
        ttk.Radiobutton(type_frame, text="组织机构代码", variable=self.type_var, value="org").pack(anchor=tk.W, pady=3)
        ttk.Radiobutton(type_frame, text="中征码", variable=self.type_var, value="zheng").pack(anchor=tk.W, pady=3)
        ttk.Radiobutton(type_frame, text="营业执照", variable=self.type_var, value="license").pack(anchor=tk.W, pady=3)
        # 结果显示
        result_frame = ttk.LabelFrame(frame, text="生成的代码", padding=10)
        result_frame.grid(row=2, column=0, columnspan=3, sticky=tk.NSEW, padx=5, pady=5)

        self.result_text = tk.Text(result_frame, height=15, width=60, font=('Consolas', 10))
        self.result_text.pack(fill=tk.BOTH, expand=True)

        # 按钮区域
        btn_frame = ttk.Frame(frame)
        btn_frame.grid(row=3, column=0, columnspan=3, pady=10)

        ttk.Button(btn_frame, text="生成", command=self.on_generate).pack(side=tk.LEFT, padx=10)
        ttk.Button(btn_frame, text="导出text", command=self.on_export).pack(side=tk.LEFT, padx=10)

    def back_to_main(self):
        """返回主界面"""
        self.root.destroy()
        from gui_main import Application
        Application().run()

    def on_generate(self):
        """生成按钮点击事件"""
        try:
            count = int(self.count_var.get())
            if count <= 0:
                raise ValueError

            if self.type_var.get() == "credit":
                codes = NumberGenerator.generate_multiple_codes(count)
            elif self.type_var.get() == "id":
                codes = NumberGenerator.generate_multiple_ids(count)
            elif self.type_var.get() == "org":
                codes = NumberGenerator.generate_multiple_orgs(count)
            elif self.type_var.get() == "zheng":
                codes = NumberGenerator.generate_multiple_zheng(count)
            elif self.type_var.get() == "license":
                codes = NumberGenerator.generate_multiple_licenses(count)

            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, "\n".join(codes))
        except ValueError:
            messagebox.showerror("错误", "请输入有效的生成数量")

    def on_export(self):
        """导出按钮点击事件"""
        content = self.result_text.get(1.0, tk.END).strip()
        if not content:
            messagebox.showerror("错误", "没有可导出的代码")
            return
        codes = content.split("\n")
        self.export_to_excel(codes)

    @staticmethod
    def export_to_excel(codes):
        """将生成的代码导出到文本文件"""
        try:
            file_path = filedialog.asksaveasfilename(
                defaultextension=".txt",
                filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")],
                title="保存生成的代码"
            )
            if file_path:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write('\n'.join(codes))
                messagebox.showinfo("导出成功", f"已成功导出到:\n{file_path}")
        except Exception as e:
            messagebox.showerror("导出错误", f"导出失败: {str(e)}")

    def run(self):
        """运行号码生成界面"""
        self.root.mainloop()
